/**
 * Created by kedong on 2017/1/5 0005.
 */
$(function () {
    /**
     * 重写表单提交事件，改成Ajax方式提交
     * @param e
     */
    $(document).on("submit", "form", function (e) {
        e.preventDefault();

        var dataArray = $(this).serializeArray(),
            // 存放表单数据
            data = {},
            // 存放表单属性
            form = {},
            attrs = this.attributes;

        /**
         * 提取表单属性
         */
        //noinspection JSDuplicatedDeclaration
        for (var i = 0, count = attrs.length; i < count; i++) {
            var node = attrs[i];
            form[node.nodeName] = node.nodeValue;
        }
        console.log(form);

        /**
         * 判断表单是否以Ajax的方式异步提交
         */
        if (form.ajax == 'false') {
            this.submit();
            return;
        }

        /**
         * 提取表单数据
         */
        if (dataArray && dataArray.length > 0) {
            //noinspection JSDuplicatedDeclaration
            for (var i = 0, count = dataArray.length; i < count; i++) {
                var item = dataArray[i];
                data[item.name] = item.value;
            }
        }

        // 异步提交表单
        loadView({
            url: form.action,
            type: form.method,
            data: data,
            async: form.async,
            container: form.container
        })
    });


});


/**
 * 通过Ajax的方式来加载html
 * @param ______option______
 */
function loadView(______option______) {
    console.log(______option______);
    $.ajax({
        url: ______option______.url,
        type: ______option______.type || "get",
        data: ______option______.data || {},
        dataType: "html",
        async: ______option______.async || false,
        success: function (__data__) {
            var container = ______option______.container || $("#main_content");
            container.html(__data__);
        },
        error: function (__data__) {
            console.log(__data__);
        }
    })
}
